package javase.javase02.networkprograming;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * @author: Gan
 * @date 2021/4/23 0023 22:19
 * @description: 发送端
 * 3.实现多线程聊天(用 UDP TCP 都可以)
 **/
public class Talks implements Runnable {
    // 将要发送的数据封装成数据包
    // DatagramPacket(byte[] buf,  int offset,
    // int length, InetAddress address, int port)
    DatagramSocket socket = null;
    BufferedReader reader = null;
    private String toIP;
    private int toPort;
    private int fromPort;

    public Talks(int fromPort, String toIP, int toPort) {
        //发送端的端口
        this.fromPort = fromPort;
        //发送到哪个IP 这里发送到本地主机 127.0.0.1
        this.toIP = toIP;
        //发送到哪个端口号 （接收端的port）
        this.toPort = toPort;

        try {
            //发送端的端口
            socket = new DatagramSocket(fromPort);
            //读入 键盘录入
            reader = new BufferedReader(new InputStreamReader(System.in));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {

        while (true) {
            try {
                //接收读入的一行行消息
                String data = reader.readLine();
                if (data.equals("bye"))
                    break;
                //封装成数据报包，准备发送出去
                byte[] bytes = data.getBytes();
                /*InetSocketAddress(InetAddress addr, int port)
                根据 IP 地址和端口号创建套接字地址。*/
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length,
                        new InetSocketAddress(this.toIP, this.toPort));
                //发送出去
                socket.send(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();

    }

}
